#!/bin/bash

script=$1
working_dir=$2
sample_list=$3

Njob=$(wc -l ${sample_list})   
Nproc=10

function CMD {        # 命令脚本
    time1=$(date)
    echo "$time1 Job $1/${Njob} Start" >> ./info/${2}_${3}_${4}.info
	bash $2 $3 $4  
	time2=$(date)
    echo "$time2 Job $1/${Njob} exiting ... Time: ${time2}-${time1}" >> ./info/${2}_${3}_${4}.info
}
function PushQue {    # 将PID压入队列
	Que="$Que $1"
	Nrun=$(($Nrun+1))
}
function GenQue {     # 更新队列
	OldQue=$Que
	Que=""; Nrun=0
	for PID in $OldQue; do
		if [[ -d /proc/$PID ]]; then
			PushQue $PID
		fi
	done
}
function ChkQue {     # 检查队列
	OldQue=$Que
	for PID in $OldQue; do
		if [[ ! -d /proc/$PID ]] ; then
			GenQue; break
		fi
	done
}


for sample in $(cat ${sample_list}); do
    Job=$(grep -n ${sample} ${sample_list})
	CMD ${Job} ${script} ${working_dir} ${sample} &
	PID=$!
	PushQue $PID
	while [[ $Nrun -ge $Nproc ]]; do
		ChkQue
		sleep 1
	done
done
wait
